<?php
namespace app\bancard\controller;

use think\Db;
use think\facade\Cache;
use app\common\lib\Curl;
use app\common\validate\TemplateValidate;
use app\bancard\model\ClassPlateTemplate as TemplateModel;
use think\facade\Env;

class Template extends Common
{
    
    //首页
    public function index()
    {
        return $this->fetch();
    }
    //列表
    public function lists()
    {
        $type = request()->param('type');
        $ntitle =request()->param('keywords');
        $title = isset($ntitle)?$ntitle:'';
        $limit = request()->param('limit');
        $offset = request()->param('offset');
        $start = ($offset-1)*$limit;
        $map =[
            'type'=>$type,
			'user_id' => session('admin.id'),
            'school_id' => session('schoolInfo.id')
        ];
        if ($title) {
            $count = db('class_plate_template')->where($map)->whereLike('title', "%$title%")->count();
            $result = db('class_plate_template')->where($map)->whereLike('title', "%$title%")->limit($start, $limit)->order('id desc,sort desc')->field('id,title,created_at,describe,image,type,show,istop,sort')->select();
        } else {
            $count = db('class_plate_template')->where($map)->count();
            $result = db('class_plate_template')->where($map)->limit($start, $limit)->order('id desc,sort desc')->field('id,title,created_at,describe,image,type,show,istop,sort')->select();
        }
        return showTable(0, 'OK', $count, $result, 200);
    }
    //查看
    public function view()
    {
        $data = request()->param();
        $result = db('class_plate_template')->where('id', $data['id'])->find();
        $this->assign('result', $result);
        return $this->fetch();
    }
	//添加
	public function add()
	{
	    if (request()->isPost()) {
	        $data = request()->param();
	        $img = $this->saveBase64Image($data['image']);
			$data['image'] = $img['image_url_path'];
	        $data['created_at'] = date('Y-m-d H:i:s', time());
	        $data['user_id'] = session('admin.id');
	        $data['school_id'] = session('schoolInfo.id');
	        $data['platform'] = 1;
	        $data['template_code'] = json_encode($data['template_code'],JSON_UNESCAPED_UNICODE);
	        $validate = new TemplateValidate;
	        
	        if (!$validate->scene('add')->check($data)) {
	            return show(0, $validate->getError(), 0, 200);
	        } else {
	            Cache::clear('class_plate_template');
	            $rest = (new TemplateModel())->strict(false)->insert($data);
	            return show(1, '添加成功', $rest, 200);
	        }
	    }
	    $components = db('components')->where(['status'=>1])->field('id,showName,brief,width,height,thumb,type,show')->select();
	    if (!empty($components)) {
	        foreach ($components as $k=>$v) {
	            $components[$k]['show'] = $v['show'] == 1?'true':'false';
	        }
	    }
	    $this->assign('components', json_encode($components));
	    return $this->fetch();
	}
	
	//添加
	public function add_v()
	{
	    if (request()->isPost()) {
	        $data = request()->param();
			$img = $this->saveBase64Image($data['image']);
			$data['image'] = $img['image_url_path'];
	        $data['created_at'] = date('Y-m-d H:i:s', time());
	        $data['user_id'] = session('admin.id');
	        $data['school_id'] = session('schoolInfo.id');
			$data['template_code'] = json_encode($data['template_code'],JSON_UNESCAPED_UNICODE);
	        $validate = new TemplateValidate;
	        if (!$validate->scene('add')->check($data)) {
	            return show(0, $validate->getError(), 0, 200);
	        } else {
	            Cache::clear('class_plate_template');
	            $rest = (new TemplateModel())->strict(false)->insert($data);
	            return show(1, '添加成功', $rest, 200);
	        }
	    }
	    $components = db('components')->where(['status'=>1])->field('id,showName,brief,width,height,thumb,type,show')->select();
	    if (!empty($components)) {
	        foreach ($components as $k=>$v) {
	            $components[$k]['show'] = $v['show'] == 1?'true':'false';
	        }
	    }
	    $this->assign('components', json_encode($components));
	    return $this->fetch();
	}
    //编辑
    public function edit()
    {
		if (request()->isPost()) {
		    $data = request()->param();
			$img = $this->saveBase64Image($data['image']);
			$data['image'] = $img['image_url_path'];
		    $data['user_id'] = session('admin.id');
		    $data['school_id'] = session('schoolInfo.id');
			$data['template_code'] = json_encode($data['template_code'],JSON_UNESCAPED_UNICODE);
		    $validate = new TemplateValidate;
		    if (!$validate->scene('edit')->check($data)) {
		        return show(0, $validate->getError(), 0, 200);
		    } else {
		        Cache::clear('class_plate_template');
		        $rest = (new TemplateModel())->strict(false)->where('id',$data['id'])->update($data);
		        return show(1, '添加成功', $rest, 200);
		    }
		}
        $data = request()->param();
        $result = db('class_plate_template')->where('id', '=', $data['id'])->find();
        $curComponents = json_decode($result['template_code'], true);
        $n = [];
        foreach ($curComponents as $kk=>$vv) {
            $n[] =$vv['id'];
        }
        $components = db('components')->where(['status'=>1])->field('id,showName,brief,width,height,thumb,type,show')->select();
        if (!empty($components)) {
            foreach ($components as $k=>$v) {
                if (in_array($v['id'], $n)) {
                    $components[$k]['show'] = false;
                } else {
                    $components[$k]['show'] = true;
                }
            }
        }
        $this->assign('components', json_encode($components));
        $this->assign('hideComponent', json_encode($n));
        $this->assign('result', $result);
        return $this->fetch();
    }
    //编辑
    public function edit_v()
    {
		if (request()->isPost()) {
		    $data = request()->param();
			$img = $this->saveBase64Image($data['image']);
			$data['image'] = $img['image_url_path'];
		    $data['user_id'] = session('admin.id');
		    $data['school_id'] = session('schoolInfo.id');
			$data['template_code'] = json_encode($data['template_code'],JSON_UNESCAPED_UNICODE);
		    $validate = new TemplateValidate;
		    if (!$validate->scene('edit')->check($data)) {
		        return show(0, $validate->getError(), 0, 200);
		    } else {
		        Cache::clear('class_plate_template');
		        $rest = (new TemplateModel())->strict(false)->where('id',$data['id'])->update($data);
		        return show(1, '添加成功', $rest, 200);
		    }
		}
        $data = request()->param();
        $result = db('class_plate_template')->where('id', '=', $data['id'])->find();
        $curComponents = json_decode($result['template_code'], true);
        $n = [];
        foreach ($curComponents as $kk=>$vv) {
            $n[] =$vv['id'];
        }
        $components = db('components')->where(['status'=>1])->field('id,showName,brief,width,height,thumb,type,show')->select();
        if (!empty($components)) {
            foreach ($components as $k=>$v) {
                if (in_array($v['id'], $n)) {
                    $components[$k]['show'] = false;
                } else {
                    $components[$k]['show'] = true;
                }
            }
        }
        $this->assign('components', json_encode($components));
        $this->assign('hideComponent', json_encode($n));
        $this->assign('result', $result);
        return $this->fetch();
    }
    //批量删除
    public function delete()
    {
        Cache::clear('class_plate_template');
        $data = request()->param();
        $result = db('class_plate_template')->where(['user_id'=>$data['user_id']])->delete($data['ids']);
        return show(1, '删除成功', $result, 200);
    }
    //是否显示
    public function show()
    {
        $data = request()->param();
        Cache::clear('class_plate_template');
        $result = db('class_plate_template')->where('id', $data['id'])->update(['show'=>$data['status']]);
        return show(1, '设置成功', $result, 200);
    }
    //是否置顶
    public function top()
    {
        $data = request()->param();
        Cache::clear('class_plate_template');
        $result = db('class_plate_template')->where('id', $data['id'])->update(['istop'=>$data['status']]);
        return show(1, '设置成功', $result, 200);
    }
    //排序
    public function sort()
    {
        $data = request()->param();
        
        $validate = new TemplateValidate;
        
        if (!$validate->scene('sort')->check($data)) {
            return show(config('code.error'), 'error', $validate->getError(), 200);
        } else {
            Cache::clear('class_plate_template');
            $rest = (new TemplateModel())->save(['sort'=>$data['sort']], ['id'=>$data['id']]);
            return show(config('code.success'), 'OK', $rest, 200);
        }
    }
	//标题编辑
	public function title_edit(){
		$data = request()->param();
		
		$validate = new TemplateValidate;
		
		if (!$validate->scene('title')->check($data)) {
		    return show(config('code.error'), 'error', $validate->getError(), 200);
		} else {
		    Cache::clear('class_plate_template');
		    $rest = (new TemplateModel())->save(['title'=>$data['title']], ['id'=>$data['id']]);
		    return show(config('code.success'), 'OK', $rest, 200);
		}
	}
	//base64转本地图片
	public function saveBase64Image($base64_image_content)
	{
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
			//图片后缀
	        $type = $result[2];
	        if ($type=='jpeg') {
	            $type='jpg';
	        }
	    
	        //保存位置--图片名
	        $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
	        $image_url = 'uploads/image/'.date('Ymd').'/'.$image_name;

            $check = $this->checkPath(dirname($image_url));


	        //解码
	        $decode=base64_decode(str_replace($result[1], '', $base64_image_content));
	        if (file_put_contents(Env::get('root_path').$image_url, $decode)) {
	            $data['code']='0';
	            $data['imageName']=$image_name;
	            $data['image_url']=$image_url;
	            $data['image_url_path']= '/'.$image_url;
	            $data['type']=$type;
	            $data['msg']='保存成功！';
	        } else {
	            $data['code']='1';
	            $data['imgageName']='';
	            $data['image_url']='';
	            $data['type']='';
	            $data['msg']='图片保存失败！';
	        }
	    } else {
	        $data['code']='1';
	        $data['imgageName']='';
	        $data['image_url']='';
	        $data['type']='';
	        $data['msg']='base64图片格式有误！';
	    }
	    return $data;
	}
    //检测目录
    protected function checkPath($path)
    {
        if (is_dir($path) || mkdir($path, 0755, true)) {
            return true;
        }

        $this->error = ['directory {:path} creation failed', ['path' => $path]];

        return false;
    }
}
